package com.own.business.irs.util;

import com.own.business.irs.constant.Constants;
import com.own.business.irs.model.IrsSignModel;
import com.own.business.irs.property.IrsProperty;
import com.own.component.common.util.encrypt.EncryptUtil;
import com.own.component.common.util.encrypt.model.CustomEncryptKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * IrsUtil
 *
 * @author chenxueli
 * @date 2023-07-02 13:32:22
 */
@Slf4j
@Component
public class IrsUtil {

    @Resource
    public IrsProperty irsProperty;

    public IrsSignModel sign(String url, String method) {
        var loginKey = irsProperty.getLogin();
        var uriComponents = UriComponentsBuilder.fromHttpUrl(url).build();
        uriComponents = uriComponents.encode();
        List<String> queryArr = new ArrayList<>();
        MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
        for (var next : queryParams.entrySet()) {
            for (String va : next.getValue()) {
                if (va == null) {
                    queryArr.add(next.getKey() + "=");
                } else {
                    queryArr.add(next.getKey() + "=" + va);
                }
            }
        }
        // 按照字典排序
        Collections.sort(queryArr);
        // Tue, 09 Nov 2021 08:49:20 GMT
        var dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        var dateTime = dateFormat.format(new Date());

        var signStr = method.toUpperCase() + "\n" +
                //拼接url path
                uriComponents.getPath() + "\n" +
                //拼接url query
                String.join("&", queryArr) + "\n" +
                loginKey.getKey() + "\n" +
                dateTime + "\n";
        var sign = EncryptUtil.HMAC_SHA_256.encrypt(loginKey.getSecret(), CustomEncryptKey.builder().secret(signStr).build());

        var model = new IrsSignModel();

        model.setSignature(sign);
        model.setAccessKey(loginKey.getKey());
        model.setDateTime(dateTime);
        model.setAlgorithm(Constants.DEFAULT_HMAC_SIGNATURE);
        return model;
    }

}
